<?php

namespace App\Service\Check\CmbBank;

use App\Models\Check\CheckCmbBankFlow;

class CmbAccountService
{
    public static function syncIncomeFlows(string $date)
    {
        $count = 0;
        $page  = 1;
        while ($page >= 1) {
            $body = CloudDirectConnectClient::accountFlow(
                $date,
                $page,
                config('check.cmb.sub_bank_code'),
                config('check.cmb.sub_account_num'),
                config('check.cmb.api_url'),
                config('check.cmb.sub_bank_public_key'),
                config('check.cmb.sub_private_key'),
                config('check.cmb.sub_sm4_key'),
                config('check.cmb.sub_uid'),
            );
            if (!$body[0]) {
                return 0;
            }
            // 分页标识
            $trsseq = intval($body[1]['data']['response']['body']['ntrbptrsz1'][0]['trsseq'] ?? 0);
            // 流水
            $flows = $body[1]['data']['response']['body']['ntqactrsz2'] ?? [];
            foreach ($flows as $flow) {
                if ($flow['trsamt'] < 0) {
                    continue;
                }
                $m              = CheckCmbBankFlow::firstOrNew([
                    'refnbr' => $flow['refnbr'],
                ]);
                $flow['etydat'] = substr($flow['etydat'], 0, 4) . '-' . substr($flow['etydat'], 4, 2) . '-' . substr($flow['etydat'], 6, 2);
                $flow['vltdat'] = substr($flow['vltdat'], 0, 4) . '-' . substr($flow['vltdat'], 4, 2) . '-' . substr($flow['vltdat'], 6, 2);
                $flow['trsblv'] = 0; // 不保存当前账户余额信息
                $m->fill($flow);
                $m->etyDateTime = $flow['etydat'] . ' ' . substr($flow['etytim'], 0, 2) . ':' . substr($flow['etytim'], 2, 2) . ':' . substr($flow['etytim'], 4, 2);
                $m->save();
                $count++;
            }

            if (count($flows) < 200 || $trsseq < ($page * 200)) {
                break;
            }
            $page++;
        }
        return $count;
    }
}
